// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package trace_cmd

import (
	"fmt"
	"time"

	"gitcode.com/opendragonfly/df_proto_gen_go.git/trace_api"
	"gitcode.com/opendragonfly/df_server/config"
	"gitcode.com/opendragonfly/df_server/utils"
	"github.com/spf13/cobra"
)

var listServiceCmd_pastHour uint32

var listServiceCmd = &cobra.Command{
	Use: "listService",
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.Port.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		client := trace_api.NewTraceApiClient(conn)
		nowTime := time.Now().UnixMilli()
		res, err := client.ListService(cmd.Context(), &trace_api.ListServiceRequest{
			AccessToken: cfg.SuperToken,
			FromTime:    nowTime - int64(listServiceCmd_pastHour)*3600*1000,
			ToTime:      nowTime,
		})
		if err != nil {
			return err
		}
		if res.Code != trace_api.ListServiceResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Println("service count", len(res.ServiceList))
		for _, service := range res.ServiceList {
			fmt.Println(service.ServiceName, service.ServiceVersion)
		}
		return nil
	},
}

func init() {
	listServiceCmd.Flags().Uint32Var(&listServiceCmd_pastHour, "pastHour", 1, "past hours from now")
}
